import Card from '@/components/Card';
import { MyChartOption } from '@/components/EchartsComponent';
import PowerStatistics from '@/pages/OverView/components/PowerStatistics';
import {
  mainPageControllerGetMainPageInfo,
  mainPageControllerGetMainPageReport,
  mainPageControllerGetPowerReport,
} from '@/services/ess/mainpageStation';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { useModel } from '@umijs/max';
import { Cascader, Flex, Space } from 'antd';
import cls from 'classnames';
import { TimeInterval } from 'd3-time';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';
import { history, Link } from 'umi';
import AlarmStatus from './components/AlarmStatus';
import IncomeStatistics from './components/IncomeStatistics';
import PowerChart from './components/PowerChart';
import SOC from './components/SOC';
import StationMonitor from './components/StationMonitor';
import StationView from './components/StationView';
import Styles from './index.less';
import NewUi from './index_newui';

interface dictType {
  label: string;
  value: string | number | undefined;
}

interface stationParamsInterface {
  stationType: string | undefined;
  startTime: string | undefined;
  startStatus: string | undefined;
  startDays: string | undefined;
  SOC: string | number | undefined;
  minSoc: number | undefined;
  maxSoc: number | undefined;
  realtimePower: string | number | undefined;
  chargeVal: string | number | undefined;
  dischargeVal: string | number | undefined;
}

interface viewInfoInterface {
  accumulateInput: number | undefined;
  accumulateOutput: number | undefined;
  chargeDischargeUnit: string | undefined;
  ratedPower: number | undefined;
  capacity: number | undefined;
  capacityUnit: string | undefined;
  ratedPowerUnit: string | undefined;
  equivalentCycles: number | undefined;
}

interface stationMonitorInterface {
  cellConnect: number | undefined;
  tmax: number | undefined;
  tmaxName: string | undefined;
  tmaxIndex: string | undefined;
  tmin: number | undefined;
  tminName: string | undefined;
  tminIndex: string | undefined;
  socMax: number | undefined;
  socMaxName: string | undefined;
  socMaxIndex: string | undefined;
  socMin: number | undefined;
  socMinName: string | undefined;
  socMinIndex: string | undefined;
  batteryType1: number | undefined;
  batteryType2: number | undefined;
  dailyAccumulateInput: number | undefined;
  dailyAccumulateOutput: number | undefined;
}

interface alarmInfoInterface {
  eventSummary: API.EventSummary;
  eventInfos: API.EventInfo[];
}

// interface CoordinateItem {
//   x: number;
//   y: number;
//   value: number | string | undefined;
//   detail: { name: string };
// }

// const socNameMap = new Map([
//   ['box', '箱名称'],
//   ['stack', '堆名称'],
//   ['cluster', '簇名称'],
// ]);
// const socNoMap = new Map([
//   ['box', '箱编号'],
//   ['stack', '堆编号'],
//   ['cluster', '簇编号'],
// ]);
const OverView: React.FC = () => {
  let StationOption: dictType[] = [];
  let runStateOption: dictType[] = [];
  let timeIntervalTask: TimeInterval;
  let chartIntervalTask: TimeInterval;
  let powerIntervalTask: TimeInterval;
  const { initialState } = useModel('@@initialState');
  const uiVersion = initialState?.uiVersion;

  // 电站概览
  const [stationInfo, changeStationInfo] = useState<stationParamsInterface>({
    stationType: '',
    startTime: '',
    startStatus: '',
    startDays: '',
    SOC: '',
    realtimePower: '',
    chargeVal: '',
    minSoc: 0,
    maxSoc: 0,
    dischargeVal: '',
  });
  // 预览信息
  const [viewInfo, setViewInfo] = useState<viewInfoInterface>({
    accumulateInput: 0,
    accumulateOutput: 0,
    ratedPower: 0,
    capacity: 0,
    equivalentCycles: 0,
    capacityUnit: '',
    ratedPowerUnit: '',
    chargeDischargeUnit: '',
  });
  // 电站监控数据
  const [stationMonitorInfo, setStationMonitor] = useState<stationMonitorInterface>({
    cellConnect: 0,
    tmax: 0,
    tmaxName: '',
    tmaxIndex: '',
    tmin: 0,
    tminName: '',
    tminIndex: '',
    socMax: 0,
    socMaxName: '',
    socMaxIndex: '',
    socMin: 0,
    socMinName: '',
    socMinIndex: '',
    batteryType1: 0,
    batteryType2: 0,
    dailyAccumulateInput: 0,
    dailyAccumulateOutput: 0,
  });
  // 告警状态
  const [alarmInfo, setAlarmInfo] = useState<alarmInfoInterface>({
    eventSummary: {},
    eventInfos: [],
  });
  // soc数据
  const [socShowOptions, setSOCShowOptions] = useState();
  const [socTypeOptions, setSocTypeOptions] = useState([]);
  const [socType, setSocType] = useState('');
  const [socInfoOptions, setSocInfoOptions] = useState<MyChartOption>({});
  // 收益统计
  const [incomeInfoOptions, setIncomeInfoOptions] = useState<MyChartOption>();
  const [incomeEndTime, setIncomeEndTime] = useState<string>(dayjs().format('YYYY-MM-DD'));
  const [incomeStartTime, setIncomeStartTime] = useState<string>(
    dayjs().subtract(6, 'day').format('YYYY-MM-DD'),
  );
  const [incomeUnit, setIncomeUnit] = useState<string>('day');
  // 充放电量统计
  const [chargeInfoOptions, setChartInfoOptions] = useState<MyChartOption>();
  const [chargeStartTime, setChargeStartTime] = useState<string>(dayjs().format('YYYY-MM-DD'));
  const [chargeEndTime, setChargeEndTime] = useState<string>(dayjs().format('YYYY-MM-DD'));
  const [chargeUnit, setChargeUnit] = useState<string>('day');
  // 充放电量功率
  const [powerChartInfo, setPowerChartInfo] = useState<MyChartOption>();
  const findChildrenByLabel = (label: string, options) => {
    // 遍历 options 数组，查找与 label 值相同的对象
    for (let i = 0; i < options.length; i++) {
      const option = options[i];
      if (option.deviceCode === label) {
        // 如果找到了与 label 值相同的对象，则返回其 children 数组
        return option.subDevices;
      } else if (option.subDevices && option.subDevices.length > 0) {
        // 如果当前对象有 children 数组，则递归查找其中与 label 值相同的对象
        const children = findChildrenByLabel(label, option.subDevices);
        if (children) {
          return children;
        }
      }
    }
    // 如果没有找到与 label 值相同的对象，则返回 null
    return null;
  };
  const getSOCOptions = (deviceCode: string, type: string = 'box') => {
    setSocInfoOptions({
      data: findChildrenByLabel(deviceCode, socTypeOptions),
      type: type,
    });
  };
  /**
   * 获得收益统计chartOptions
   * @param options
   */
  const formatterIncomeOptions = (options: API.ReportTable, unit?: string): MyChartOption => {
    const xAxis = options?.xaxis;
    const yAxisMap = options?.yaxis[0].points.reduce((acc, current) => {
      acc[current.xaxis] = current.yaxis;
      return acc;
    }, {});
    const seriesData = options?.xaxis.map((date) => {
      return yAxisMap[date] !== undefined ? yAxisMap[date] : 0;
    });
    return {
      xAxis: {
        type: 'category',
        data: xAxis,
        axisTick: {
          alignWithLabel: true,
        },
        axisLabel: {
          formatter: function (value) {
            return unit === 'day' ? value.split('-')[1] + '-' + value.split('-')[2] : value;
          },
        },
      },
      grid: {
        left: 50,
        top: 35,
        right: 0,
        bottom: 30,
      },
      dataZoom: { type: 'inside' },

      tooltip: {
        show: true,
        trigger: 'axis',
      },
      yAxis: {
        name: options?.yaxis[0].title,
        type: 'value',
        axisLine: {
          show: true,
        },
      },
      series: [
        {
          data: seriesData,
          itemStyle: {
            color: '#1A6CFE',
          },
          type: 'bar',
        },
      ],
    };
  };
  /**
   * 获得充放电量统计
   * @param options
   */
  const formatterChargeOptions = (options: API.ReportTable): MyChartOption => {
    const xAxis = options?.xaxis;
    // 获得充电量Map
    const chargeDataMap = options?.yaxis[0].points.reduce((acc, current) => {
      acc[current.xaxis] = current.yaxis;
      return acc;
    }, {});
    const chargeData = options?.xaxis.map((date) => {
      return chargeDataMap[date] !== undefined ? chargeDataMap[date] : '';
    });
    // 获得放电量Map
    const dischargeDataMap = options?.yaxis[1]?.points.reduce((acc, current) => {
      acc[current.xaxis] = current.yaxis;
      return acc;
    }, {});
    const dischargeData = options?.xaxis.map((date) => {
      return dischargeDataMap[date] !== undefined ? dischargeDataMap[date] : '';
    });
    return {
      dataZoom: {
        type: 'inside',
      },
      xAxis: {
        type: 'category',
        data: xAxis,
        boundaryGap: true,
        axisTick: {
          alignWithLabel: true,
        },
        axisLabel: {
          formatter: function (value, index) {
            return index + 1;
          },
        },
      },
      grid: {
        left: 50,
        top: 35,
        right: 0,
        bottom: 30,
      },
      yAxis: {
        name: 'kWh',
        type: 'value',
        axisLine: {
          show: true,
        },
      },
      tooltip: {
        show: true,
        trigger: 'axis',
      },
      legend: {
        show: true,
        top: 10,
        right: 0,
        icon: 'circle',
      },
      series: [
        // 充电量
        {
          name: '充电量',
          data: chargeData,
          itemStyle: {
            color: '#67C23A',
          },
          type: 'bar',
        },
        // 放电量
        {
          name: '放电量',
          data: dischargeData,
          itemStyle: {
            color: '#FFD50C',
          },
          type: 'bar',
        },
      ],
    };
  };
  /**
   * 获得当日充放电功率图
   * @param options
   */
  const formatterPowerChartOptions = (options: API.ReportTable): MyChartOption => {
    // const xAxis = options?.yaxis[0].points.map((item) => {
    //   return item.xaxis;
    // });
    // const yaxis = options?.yaxis[0].points.map((item) => {
    //   return item.yaxis;
    // });
    const seriesData = options?.xaxis.map((item: string) => {
      const obj = options?.yaxis[0].points.find((obj) => obj.xaxis === item);
      return obj ? obj.yaxis : '';
    });
    return {
      grid: {
        top: 40,
        left: 50,
        right: 0,
        bottom: 24,
      },
      dataZoom: { type: 'inside' },
      xAxis: {
        boundaryGap: true,
        type: 'category',
        data: options?.xaxis,
        axisLabel: {
          formatter: function (value) {
            return `${value.split(' ')[1].slice(0, 2)}`;
          },
          interval: 120,
        },
        axisTick: {
          alignWithLabel: true,
        },
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}<br/>功率  {c}',
      },
      yAxis: {
        type: 'value',
        name: options.yaxis[0].title,
        axisLine: {
          show: true,
        },
      },
      series: [
        {
          connectNulls: true,
          name: 'power',
          type: 'line',
          data: seriesData,
          smooth: true,
          symbolSize: 1,
          lineStyle: {
            color: '#1A6CFE',
            // shadowColor: '#1A6CFE',
            // shadowBlur: 30,
            // shadowOffsetY: 10,
          },
        },
      ],
    };
  };
  /**
   * 获得soc箱图
   * @param options
   */
  // const formatterSOCChartOptions = (options, type?): MyChartOption => {
  //   if (!options) return false;
  //   let coordinates: CoordinateItem[][] = [];
  //   let x = 0;
  //   let y = Math.floor(options?.length / 3);
  //   console.log('x: ' + x + ' y: ' + y);
  //   options.forEach((item, index) => {
  //     if (index > 0 && index % 3 === 0) {
  //       y--;
  //       x = 0;
  //     }
  //     console.log('coorX', x, 'coorY', y);
  //     coordinates.push([
  //       x,
  //       y,
  //       item.soc || 0,
  //       {
  //         detail:
  //           type === 'box' ? item.boxCode : type === 'stack' ? item.bmsCode : item.clusterCode,
  //         name: type === 'box' ? item.boxName : type === 'stack' ? item.bmsName : item.clusterName,
  //       },
  //     ]);
  //     console.log('coordinates', coordinates);
  //     ++x;
  //   });
  //   const demo = [
  //     [0, 0, null],
  //     [0, 1, 10, { detail: '箱1', name: '001' }],
  //     [1, 1, 20, { detail: '箱2', name: '002' }],
  //     [2, 1, 30, { detail: '箱3', name: '003' }],
  //   ];
  //   return {
  //     // 滚动条样式
  //     dataZoom: {
  //       fillerColor: '#FCFCFC',
  //       backgroundColor: '#D3D7E1',
  //       width: 12,
  //       maxValueSpan: 3,
  //       type: 'slider',
  //       realtime: true,
  //       zoomLock: false,
  //       orient: 'vertical',
  //       showDetail: false,
  //       moveOnMouseWheel: true,
  //       brushSelect: false,
  //       handleStyle: {
  //         opacity: 0,
  //       },
  //       handleSize: 0,
  //       zoomOnMouseWheel: false,
  //       moveHandleStyle: {
  //         opacity: 0,
  //         color: '#0F66FF',
  //       },
  //     },
  //     tooltip: {
  //       position: 'top',
  //       // formatter: function (params) {
  //       //     let dataItem = coordinates[params.dataIndex];
  //       //     let detail = dataItem[3]?.detail; // 获取detail属性
  //       //     let name = dataItem[3]?.name ? dataItem[3]?.name : '';
  //       //     return (
  //       //       `${socNameMap.get(type)}：` +
  //       //       name +
  //       //       '<br>' +
  //       //       'SOC: ' +
  //       //       params.value[2] +
  //       //       '<br>' +
  //       //       `${socNoMap.get(type)}：` +
  //       //       detail
  //       //     );
  //       //   },
  //     },
  //     grid: {
  //       show: true,
  //       right: 10,
  //       top: '5%',
  //       left: 0,
  //       height: '50%',
  //     },
  //     xAxis: {
  //       show: false,
  //       type: 'category',
  //     },
  //     yAxis: {
  //       show: false,
  //       type: 'category',
  //     },
  //     visualMap: {
  //       itemHeight: 200,
  //       text: ['', 'SOC'],
  //       min: 0,
  //       max: 100,
  //       color: ['#0F66FF', '#D1E2FE'],
  //       calculable: true,
  //       orient: 'horizontal',
  //       left: 'center',
  //       bottom: '15%',
  //     },
  //     series: [
  //       {
  //         name: 'Punch Card',
  //         type: 'heatmap',
  //         // data: coordinates.map(function (item) {
  //         //   return [item[0], item[1], item[2]]; // 只返回前三个元素（x, y, value）
  //         // }),
  //         data: demo.map(function (item) {
  //           return [item[0], item[1], item[2]]; // 只返回前三个元素（x, y, value）
  //         }),
  //         // label: {
  //         //   show: true,
  //         //   formatter: function (params) {
  //         //     let dataItem = coordinates[params.dataIndex];
  //         //     return dataItem[3].name; // 获取detail属性
  //         //   },
  //         // },
  //         itemStyle: {
  //           borderColor: '#fff',
  //           borderWidth: 2,
  //         },
  //       },
  //     ],
  //   };
  // };
  const clickSOC = (e) => {
    history.push('/monitor/battery', {
      data: {
        socData: e,
      },
    });
  };
  const getChartInfo = (params) => {
    mainPageControllerGetMainPageReport(params).then((res) => {
      setIncomeInfoOptions(formatterIncomeOptions(res?.data?.incomeReport, params.incomeUnit));
      setChartInfoOptions(formatterChargeOptions(res?.data?.chargeDischargeReport));
    });
  };
  /**
   * 获得功率图
   */
  const getPowerChartInfo = () => {
    mainPageControllerGetPowerReport({ stationId: initialState?.stationId }).then((res) => {
      if (res.success) {
        setPowerChartInfo(formatterPowerChartOptions(res?.data));
      }
    });
  };
  const getMainPageInfo = (params: API.mainPageControllerGetMainPageInfoParams) => {
    mainPageControllerGetMainPageInfo(params).then((res) => {
      if (res.success && res?.data && Object.keys(res.data).length > 0) {
        changeStationInfo({
          stationType: StationOption.filter(
            (item) => item.value === res?.data?.stationInfo?.stationType,
          )[0]?.label,
          startDays: res?.data?.runTime || '0',
          startTime: res?.data?.stationInfo?.startRunTime?.substring(0, 10) || null,
          startStatus: runStateOption.filter(
            (item) => item.value === res?.data?.stationInfo?.runStatus,
          )[0]?.label,
          SOC: res?.data?.stationSoc,
          realtimePower: res?.data?.totalPower,
          chargeVal: res?.data?.usedEnergy || 0,
          minSoc: res?.data?.stationInfo?.minSoc || 0,
          maxSoc: res?.data?.stationInfo?.maxSoc || 0,
          dischargeVal: res?.data?.leftEnergy || 0,
        });
        // 电站概览
        setViewInfo({
          accumulateInput: res?.data?.accumulateInput || 0,
          accumulateOutput: res?.data?.accumulateOutput || 0,
          chargeDischargeUnit: res?.data?.stationInfo?.chargeDischargeUnit,
          ratedPowerUnit: res?.data?.stationInfo?.ratedPowerUnit,
          capacityUnit: res?.data?.stationInfo?.capacityUnit,
          ratedPower: res?.data?.stationInfo?.ratedPower || 0,
          capacity: res?.data?.stationInfo?.capacity || 0,
          equivalentCycles: res?.data?.equivalentCycles || 0,
        });
        // 电站监测
        setStationMonitor({
          cellConnect: res?.data?.stationInfo?.cellConnect,
          tmax: res?.data?.tmax,
          tmaxName: res?.data?.tmaxName,
          tmaxIndex: res?.data?.tmaxIndex,
          tmin: res?.data?.tmin,
          tminName: res?.data?.tminName,
          tminIndex: res?.data?.tminIndex,
          socMax: res?.data?.socMax,
          socMaxName: res?.data?.socMaxName,
          socMaxIndex: res?.data?.socMaxIndex,
          socMin: res?.data?.socMin,
          socMinName: res?.data?.socMinName,
          socMinIndex: res?.data?.socMinIndex,
          batteryType1: res?.data?.stationInfo?.batteryType1,
          batteryType2: res?.data?.stationInfo?.batteryType2,
          dailyAccumulateInput: res?.data?.dailyAccumulateInput,
          dailyAccumulateOutput: res?.data?.dailyAccumulateOutput,
        });
        setAlarmInfo({
          eventSummary: res?.data?.eventSummary || {},
          eventInfos: res?.data?.eventInfos || [],
        });
        if (res.data.deviceVOs) {
          const initSocOptions = [
            {
              deviceCode: '000',
              deviceName: initialState?.stationName,
              subDevices: res?.data?.deviceVOs,
            },
          ];

          /**
           * 去除掉簇维度
           * @param initSocOptions
           */
          function getTotalSOCOptions(initSocOptions) {
            const option = JSON.parse(JSON.stringify(initSocOptions));
            option[0].subDevices.forEach((item, index) => {
              item.subDevices.forEach((lItem, lIndex) => {
                option[0].subDevices[index].subDevices[lIndex].subDevices = [];
              });
            });
            return option;
          }

          setSOCShowOptions(getTotalSOCOptions(initSocOptions));
          setSocTypeOptions(initSocOptions);
          setSocType('000');
          setSocInfoOptions({ data: findChildrenByLabel('000', initSocOptions), type: 'box' });
        }
      }
    });
  };
  /**
   * 收益统计查询
   * @param value
   */
  const getIncomeInfo = (value) => {
    const params = {
      stationId: initialState?.stationId,
      incomeStartTime: value.incomeStartTime,
      incomeEndTime: value.incomeEndTime,
      incomeUnit: value.incomeUnit,
      chargeStartTime: chargeStartTime,
      chargeEndTime: chargeEndTime,
      chargeUnit: chargeUnit,
    };
    getChartInfo(params);
    setIncomeStartTime(value.incomeStartTime);
    setIncomeEndTime(value.incomeEndTime);
    setIncomeUnit(value.incomeUnit);
  };
  /**
   * 充放电量统计查询
   * @param value
   */
  const getChargeInfo = (value) => {
    const params = {
      stationId: initialState?.stationId,
      incomeStartTime: incomeStartTime,
      incomeEndTime: incomeEndTime,
      incomeUnit: incomeUnit,
      chargeStartTime: value.chargeStartTime,
      chargeUnit: value.chargeUnit,
    };
    getChartInfo(params);
    setChargeStartTime(value.chargeStartTime);
    setChargeEndTime(value.chargeEndTime);
    setChargeUnit(value.chargeUnit);
  };
  /**
   * 每十秒刷新页面的回调函数
   * @param params
   */
  const gerRefreshPageInfo = (params) => {
    mainPageControllerGetMainPageInfo(params).then((res) => {
      if (res.success && res.data && Object.keys(res.data).length > 0) {
        changeStationInfo({
          stationType: StationOption.filter(
            (item) => item.value === res?.data?.stationInfo?.stationType,
          )[0]?.label,
          startDays: res?.data?.runTime || '0',
          startTime: res?.data?.stationInfo?.startRunTime?.substring(0, 10) || null,
          startStatus: runStateOption.filter(
            (item) => item.value === res?.data?.stationInfo?.runStatus,
          )[0]?.label,
          SOC: res?.data?.stationSoc,
          realtimePower: res?.data?.totalPower,
          chargeVal: res?.data?.usedEnergy || 0,
          minSoc: res?.data?.stationInfo?.minSoc || 0,
          maxSoc: res?.data?.stationInfo?.maxSoc || 0,
          dischargeVal: res?.data?.leftEnergy || 0,
        });
        // 电站概览
        setViewInfo({
          accumulateInput: res?.data?.accumulateInput || 0,
          accumulateOutput: res?.data?.accumulateOutput || 0,
          chargeDischargeUnit: res?.data?.stationInfo?.chargeDischargeUnit,
          ratedPowerUnit: res?.data?.stationInfo?.ratedPowerUnit,
          capacityUnit: res?.data?.stationInfo?.capacityUnit,
          ratedPower: res?.data?.stationInfo?.ratedPower || 0,
          capacity: res?.data?.stationInfo?.capacity || 0,
          equivalentCycles: res?.data?.equivalentCycles || 0,
        });
        // 电站监测
        setStationMonitor({
          cellConnect: res?.data?.stationInfo?.cellConnect,
          tmax: res?.data?.tmax,
          tmaxName: res?.data?.tmaxName,
          tmaxIndex: res?.data?.tmaxIndex,
          tmin: res?.data?.tmin,
          tminName: res?.data?.tminName,
          tminIndex: res?.data?.tminIndex,
          socMax: res?.data?.socMax,
          socMaxName: res?.data?.socMaxName,
          socMaxIndex: res?.data?.socMaxIndex,
          socMin: res?.data?.socMin,
          socMinName: res?.data?.socMinName,
          socMinIndex: res?.data?.socMinIndex,
          batteryType1: res?.data?.stationInfo?.batteryType1,
          batteryType2: res?.data?.stationInfo?.batteryType2,
          dailyAccumulateInput: res?.data?.dailyAccumulateInput,
          dailyAccumulateOutput: res?.data?.dailyAccumulateOutput,
        });
        setAlarmInfo({
          eventSummary: res?.data?.eventSummary || {},
          eventInfos: res?.data?.eventInfos || [],
        });

        //soc相关数据增加实时更新
        if (res.data.deviceVOs) {
          const initSocOptions = [
            {
              deviceCode: '000',
              deviceName: initialState?.stationName,
              subDevices: res?.data?.deviceVOs,
            },
          ];

          /**
           * 去除掉簇维度
           * @param initSocOptions
           */
          function getTotalSOCOptions(initSocOptions) {
            const option = JSON.parse(JSON.stringify(initSocOptions));
            option[0].subDevices.forEach((item, index) => {
              item.subDevices.forEach((lItem, lIndex) => {
                option[0].subDevices[index].subDevices[lIndex].subDevices = [];
              });
            });
            return option;
          }

          setSOCShowOptions(getTotalSOCOptions(initSocOptions));
          setSocTypeOptions(initSocOptions);
          setSocType('000');
          setSocInfoOptions({ data: findChildrenByLabel('000', initSocOptions), type: 'box' });
        }

        // setPowerChartInfo(formatterPowerChartOptions(res?.data?.dailyPowerReport));
      }
    });
  };
  /**
   * 数据换算
   * @param num
   */
  const dataConversion = (num: number): number => {
    let data = JSON.parse(JSON.stringify(num));
    data =
      data > 1000
        ? (data / 1000).toFixed(2)
        : data > 1000000
        ? (data / 1000000).toFixed(2)
        : data.toFixed(2);
    return data;
  };
  useEffect(() => {
    if (uiVersion === 1) {
      if (timeIntervalTask) {
        clearInterval(timeIntervalTask);
      }
      if (chartIntervalTask) {
        clearInterval(chartIntervalTask);
      }
      if (powerIntervalTask) {
        clearInterval(powerIntervalTask);
      }
      if (initialState?.stationId) {
        fetchDictInfo(DATABASE_TYPE_ENUM.SITE_TYPE).then((res) => {
          StationOption = res;
        });
        fetchDictInfo(DATABASE_TYPE_ENUM.OVERVIEW_RUN_STATUS, true).then((res) => {
          runStateOption = res;
        });
        const params = {
          stationId: initialState?.stationId,
          incomeStartTime: incomeStartTime,
          incomeEndTime: incomeEndTime,
          incomeUnit: incomeUnit,
          chargeStartTime: chargeStartTime,
          chargeUnit: chargeUnit,
        };
        getMainPageInfo(params);
        getChartInfo(params);
        getPowerChartInfo();
        timeIntervalTask = setInterval(() => {
          gerRefreshPageInfo(params);
        }, 10000);
        chartIntervalTask = setInterval(() => {
          getChartInfo(params);
        }, 3600000);
        powerIntervalTask = setInterval(() => {
          getPowerChartInfo();
        }, 2000);
      }

      return () => {
        clearInterval(timeIntervalTask);
        clearInterval(chartIntervalTask);
        clearInterval(powerIntervalTask);
      };
    }
  }, [initialState?.stationId]);

  return uiVersion === 1 ? (
    <div className={Styles.view}>
      <div className={Styles.tagGather}>
        <div className={cls([Styles.AccumulateCharge, Styles.AlarmBox])}>
          <div>累计充电量</div>
          <div>
            {dataConversion(viewInfo.accumulateInput)}
            <span className={Styles.AlarmBoxUnit}>
              {viewInfo?.accumulateOutput > 1000
                ? 'MWh'
                : viewInfo?.accumulateOutput > 1000000
                ? 'GWh'
                : 'kWh'}
            </span>
          </div>
        </div>
        <div className={cls([Styles.AccumulateDischarge, Styles.AlarmBox])}>
          <div>累计放电量</div>
          <div>
            {dataConversion(viewInfo.accumulateOutput)}
            <span className={Styles.AlarmBoxUnit}>
              {viewInfo?.accumulateOutput > 1000
                ? 'MWh'
                : viewInfo?.accumulateOutput > 1000000
                ? 'GWh'
                : 'kWh'}
            </span>
          </div>
        </div>
        <div className={cls([Styles.CycleTimes, Styles.AlarmBox])}>
          <div>等效循环次数</div>
          <div>
            {viewInfo.equivalentCycles}
            <span className={Styles.AlarmBoxUnit}>次</span>
          </div>
        </div>
        <div className={cls([Styles.RatedPower, Styles.AlarmBox])}>
          <div>额定功率</div>
          <div>
            {viewInfo.ratedPower}
            <span className={Styles.AlarmBoxUnit}>{viewInfo.ratedPowerUnit}</span>
          </div>
        </div>
        <div className={cls([Styles.RatedCapacity, Styles.AlarmBox])}>
          <div>额定容量</div>
          <div>
            {viewInfo.capacity}
            <span className={Styles.AlarmBoxUnit}>{viewInfo.capacityUnit}</span>
          </div>
        </div>
      </div>
      <Flex justify="space-between" className={Styles.viewContent}>
        <Flex vertical={true} className={Styles.viewBoxLeft}>
          <Card title="电站概览" className={Styles.topCard}>
            <StationView stationInfo={stationInfo} />
          </Card>
          <Card
            title="SOC"
            className={Styles.topCardSOC}
            extra={
              <div>
                <Space>
                  <Cascader
                    allowClear={false}
                    value={socType}
                    options={socShowOptions}
                    fieldNames={{
                      label: 'deviceName',
                      value: 'deviceCode',
                      children: 'subDevices',
                    }}
                    style={{ width: 'auto', minWidth: 80, maxWidth: 160 }}
                    changeOnSelect={true}
                    onChange={(e) => {
                      if (e) {
                        setSocType(e);
                        if (e.length === 1) {
                          getSOCOptions(e[0], 'box');
                        } else {
                          getSOCOptions(e.at(-1), 'stack');
                        }
                      }
                    }}
                    size="small"
                  ></Cascader>
                </Space>
              </div>
            }
          >
            <SOC socInfoOptions={socInfoOptions} clickSOC={clickSOC} />
          </Card>
        </Flex>
        <Flex vertical={true} className={Styles.viewBoxRight}>
          <Card title="电站监测" className={Styles.topCardStationView}>
            <StationMonitor monitorData={stationMonitorInfo} />
          </Card>
          <Card
            title="告警状态"
            className={Styles.topCardAlarm}
            extra={
              <div className={Styles.AlarmText}>
                <Flex>
                  <div
                    className={Styles.AlarmInfoBox}
                    style={{
                      backgroundColor: '#F54E4B',
                    }}
                  >
                    事故
                    {Number(alarmInfo?.eventSummary.error) > 99
                      ? '99+'
                      : alarmInfo?.eventSummary.error}
                  </div>
                  <div className={Styles.AlarmInfoBox} style={{ backgroundColor: '#FF7A0C' }}>
                    告警
                    {Number(alarmInfo?.eventSummary.warn) > 99
                      ? '99+'
                      : alarmInfo?.eventSummary.warn}
                  </div>
                  <div className={Styles.AlarmInfoBox} style={{ backgroundColor: '#FFD50C' }}>
                    通知
                    {Number(alarmInfo?.eventSummary.info) > 99
                      ? '99+'
                      : alarmInfo?.eventSummary.info}
                  </div>
                  {/*<div className={Styles.AlarmBox} style={{ backgroundColor: '#67C23A' }}>*/}
                  {/*  预警{eventSummary.info}*/}
                  {/*</div>*/}
                </Flex>
                <Link to={'/alarm/list'}>
                  <div
                    className={Styles.DetailText}
                    style={{ marginLeft: '10px', cursor: 'pointer' }}
                  >
                    <span>详情</span>
                    <span>{'>'}</span>
                  </div>
                </Link>
              </div>
            }
          >
            <AlarmStatus alarmInfo={alarmInfo} />
          </Card>
        </Flex>
      </Flex>
      <Flex justify="space-between" className={Styles.ChartContent}>
        <Card title="收益统计" className={Styles.bottomCard}>
          <IncomeStatistics
            incomeInfoOptions={incomeInfoOptions}
            sendIncomeTimeInfo={getIncomeInfo}
          />
        </Card>
        <Card title="充放电量统计" className={Styles.bottomCard}>
          <PowerStatistics chargeInfoOptions={chargeInfoOptions} sendChargeInfo={getChargeInfo} />
        </Card>
        <Card
          title={
            <div>
              <Flex justify={'space-between'} align={'center'}>
                <div>{'当日充放电功率图'}</div>
                <div>
                  <Link to={'/strategy/track?tab=2'}>
                    <div
                      className={Styles.DetailText}
                      style={{ fontSize: '14px', cursor: 'pointer', fontWeight: 'normal' }}
                    >
                      <span>详情</span>
                      <span>{'>'}</span>
                    </div>
                  </Link>
                </div>
              </Flex>
            </div>
          }
          className={Styles.bottomCard}
        >
          <PowerChart powerChartInfo={powerChartInfo} />
        </Card>
      </Flex>
      <div className={Styles.bg}></div>
      {/*<div className={Styles.Report}>*/}
      {/*  <MonthlyReport isViewFlag={true} />*/}
      {/*</div>*/}
    </div>
  ) : (
    <NewUi />
  );
};

export default OverView;
